#include <REGX52.H> 
#define ATAddress 0xA0
 
sbit SDA=P2^0;
sbit SCL=P2^1;

unsigned char i=0;

void I2C_Start()
{
	SDA=1;
	SCL=1;
	SDA=0;
	SCL=0;
}

void I2C_Send(unsigned char B)
{
	for(i=0;i<8;i++)
	{
		SDA =B &(0x80>>i);
		SCL=1;
		SCL=0;
	}
}

unsigned char I2C_Receive()
{
	unsigned char B=0x00;
	SDA=1;
	for(i=0;i<8;i++)
	{	
		SCL=1;
		if(SDA)
		{
			B|=(0x80>>i);
		}
		SCL=0;
	}
	return B;
}

void I2C_SendACK(unsigned char Bit)
{
	SDA=Bit;
	SCL=1;
	SCL=0;
}

unsigned char I2C_ReceiveACK()
{
	unsigned char B=0;
	SDA=1;
	SCL=1;
	if(SDA)B=1;
	SCL=0;
	return B;
}

void I2C_Stop()
{
	SDA=0;
	SCL=1;
	SDA=1;
}

void I2C_SendMessage(unsigned char address,byte)
{
	I2C_Start();
	I2C_Send(ATAddress);
	I2C_ReceiveACK();
	I2C_Send(address);
	I2C_ReceiveACK();
	I2C_Send(byte);
	I2C_ReceiveACK();
	I2C_Stop();
}
unsigned char I2C_ReceiveMessage(unsigned char address)
{
	unsigned char B=0; 
	I2C_Start();
	I2C_Send(ATAddress);
	I2C_ReceiveACK();
	I2C_Send(address);
	I2C_ReceiveACK();
	I2C_Start();
	I2C_Send(ATAddress|0x01);
	I2C_ReceiveACK();
	B=I2C_Receive();
	I2C_SendACK(1);
	return B;
}
